import base64
import json

import pickle
from django import http
from django.shortcuts import render
from django_redis import get_redis_connection
# Create your views here.
from django.views import View

from goods.models import SKU
from meiduo_mall.utils.response_code import RETCODE


class CartsView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected')

        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少参数')

        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在')

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('数量不为数字')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selecter类型错误')

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hincrby('carts_%s' % request.user.id, sku_id, count)
            if selected:
                pl.hadd('carts_%s' % request.user.id, sku_id)

            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK,
                                      'errmsg': 'ok'})
        else:
            cookie_cart = request.COOKIES.get('carts')

            if cookie_cart:
                cart_dict = pickle.loads(base64.b16decode(cookie_cart.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_date = base64.b16decode(pickle.dumps(cart_dict)).decode()

            response = http.JsonResponse({'code': RETCODE.OK,
                                          'errmsg': 'ok'})
            response.set_cookie('carts', cart_date)

            return response

    def get(self, request):
        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            carts_dict = {}
            for sku_id, count in cart_dict.items():
                carts_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            cookie_cart = request.COOKIES.get('carts')

            if cookie_cart:
                carts_dict = pickle.loads(base64.b16decode(cookie_cart.encode()))
            else:
                carts_dict = {}

        sku_ids = carts_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        sku_carts = []
        for sku in skus:
            sku_carts.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': str(cart_dict.get(sku.id).get('selected')),
                'default_image_url': sku.default_image_url,
                'price': str(sku.price),
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })

        context = {
            'cart_skus': sku_carts
        }

        return render(request, 'cart.html', context)

    def put(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected')

        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少参数')

        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('sku_id不存在')

        try:
            count = int(count)
        except Exception as e:
            return http.HttpResponseForbidden('count格式错误')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selected格式错误')

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hset('cart_%s' % user.id, sku_id, count)

            if selected:
                pl.sadd('cart_%s' % user.id, sku_id)
            else:
                pl.srem('cart_%s' % user.id, sku_id)

            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * count,
            }
            return http.JsonResponse({'code': RETCODE.OK,
                                      'errmsg': 'ok',
                                      'cart_sku': cart_sku})
        else:
            cookie_cart = request.COOKIES.get('carts')

            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }
            cart_date = base64.b64encode(pickle.dumps(cart_dict)).decode()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * count,
            }

            response = http.JsonResponse({'code': RETCODE.OK,
                                          'errmsg': 'ok',
                                          'cart_sku': cart_sku})
            response.set_cookie('carts', cart_date)

            return response

    def delete(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            return http.HttpResponseForbidden('商品不存在')

        user = request.user

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hdel('cart_%s' % user.id, sku_id)
            pl.srem('selected_%s' % user.id, sku_id)

            pl.execute()

            return http.JsonResponse({'code': RETCODE.OK,
                                      'errmsg': 'ok'})
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}

            response = http.JsonResponse({'code': RETCODE.OK,
                                          'errmsg': 'ok'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie('carts', cart_data)

            return response


class CartsSelectionView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected')

        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('selected类型错误')

        user = request.user
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            cart_dict = redis_conn.hgetall('cart_%s' % user.id)
            sku_ids = cart_dict.keys()

            if selected:
                redis_conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_ids)

            return http.JsonResponse({'code': RETCODE.OK,
                                      'errmsg': 'ok'})
        else:
            cookie_dict = request.COOKIES.get('carts')

            response = http.JsonResponse({'code': RETCODE.OK,
                                          'errmsg': 'ok'})

            if cookie_dict:
                cart_dict = pickle.loads(base64.b64decode(cookie_dict.encode()))

                for sku_id in cart_dict:
                    cart_dict[sku_id]['selected'] = selected
                    cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
                    response.set_cookie('carts', cart_data)

                return response


class CartsSimpleView(View):
    def get(self, request):
        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('cart_%s' % user.id)
            cart_selected = redis_conn.smembers('cart_%s' % user.id)

            cart_dict = {}
            for sku_id, count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}

        cart_skus = []
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image_url
            })
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'cart_skus': cart_skus})